package com.ruoyi.develop.goodsCustomer.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.DateUtils;
        import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.goodsSale.domain.GoodsSale;
import com.ruoyi.develop.projectBaseInfo.domain.ProjectBaseInfo;
import com.ruoyi.export.service.impl.ExportServiceImpl;
import org.apache.poi.ss.usermodel.DateUtil;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.develop.goodsCustomer.mapper.GoodsCustomerMapper;
import com.ruoyi.develop.goodsCustomer.domain.GoodsCustomer;
import com.ruoyi.develop.goodsCustomer.service.IGoodsCustomerService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 客户信息管理Service业务层处理
 * @author qh
 * @date 2023-01-05
 */
@Service
public class GoodsCustomerServiceImpl implements IGoodsCustomerService {
    @Resource
    private GoodsCustomerMapper goodsCustomerMapper;

    @Value(value = "${ruoyi.path}")
    public String basePath;
    @Value(value = "${ruoyi.templatePath}")
    public String templatePath;
    @Value(value = "${ruoyi.templateImport}")
    public String templateImport;
    @Autowired
    private ExportServiceImpl exportService;

    /**
     * 查询客户信息管理
     * @param id 客户信息管理主键
     * @return 客户信息管理
     */
    @Override
    public GoodsCustomer selectById(String id) {
        return goodsCustomerMapper.selectById(id);
    }

    @Override
    public GoodsCustomer selectByName(String name) {
        return goodsCustomerMapper.selectByName(name);
    }

    @Override
    public GoodsCustomer selectByCode(String code) {
        return goodsCustomerMapper.selectByCode(code);
    }

    @Override
    public String getMaxCodeByArea(String area) {
        return goodsCustomerMapper.getMaxCodeByArea(area);
    }

    @Override
    public String getMaxCode() {
        return goodsCustomerMapper.getMaxCode();
    }

    @Override
    public void exportData(HttpServletRequest request, HttpServletResponse response, GoodsCustomer entity) {
        List<GoodsCustomer> list = goodsCustomerMapper.selectList(entity);
        String fileName = "客户信息导出列表.xlsx";
        String templateName = "客户信息导出模板.xlsx";
        Map<String, Object> params = new HashMap<>();
        // 翻译字典
        list.stream().forEach(e -> {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("area", DictUtils.getDictLabel("order_area", e.getArea()));
            e.setParams(map);
        });
        params.put("list", list);
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
    }

    /**
     * 查询客户信息管理列表
     * @param entity 客户信息管理
     * @return 客户信息管理
     */
    @Override
    public List<GoodsCustomer> selectList(GoodsCustomer entity) {
        return goodsCustomerMapper.selectList(entity);
    }

    /**
     * 新增客户信息管理
     * @param entity 客户信息管理
     * @return 结果
     */
    @Override
    public int insert(GoodsCustomer entity) {
        if(StringUtils.isBlank(entity.getId())){
            entity.setId(IdUtils.fastSimpleUUID());
        }
                entity.setCreateBy(SecurityUtils.getUsername());
                entity.setCreateTime(DateUtils.getNowDate());
            return goodsCustomerMapper.insert(entity);
    }

    @Override
    public String checkNameUnique(String name) {
        int count = goodsCustomerMapper.checkNameUnique(name);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
    /**
     * 修改客户信息管理
     * @param entity 客户信息管理
     * @return 结果
     */
    @Override
    public int update(GoodsCustomer entity) {
                entity.setUpdateBy(SecurityUtils.getUsername());
                entity.setUpdateTime(DateUtils.getNowDate());
        return goodsCustomerMapper.update(entity);
    }

    /**
     * 批量删除客户信息管理
     * @param ids 需要删除的客户信息管理主键
     * @return 结果
     */
    @Override
    public int deleteByIds(String[] ids) {
        return goodsCustomerMapper.deleteByIds(ids);
    }

    /**
     * 删除客户信息管理信息
     * @param id 客户信息管理主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return goodsCustomerMapper.deleteById(id);
    }

    @Override
    public List<SysDictData> selectAllCustomers() {
        List<SysDictData> dictDatas = new ArrayList<>();
        List<GoodsCustomer> lists = selectList(new GoodsCustomer());
        lists.stream().forEach(entity -> {
            SysDictData dict = new SysDictData();
            dict.setDictLabel(entity.getName());
            dict.setDictValue(entity.getId());
            dictDatas.add(dict);
        });
        return dictDatas;
    }

    @Override
    public List<GoodsCustomer> selectAllSupp(GoodsCustomer entity) {
        return goodsCustomerMapper.selectAllSupp(entity);
    }


    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Map<String, Object> importData(GoodsCustomer contact, MultipartFile file) {
        String tmplName = "goodsCustomer.xml";
        String errortext = "";
        Map<String, Object> map = new HashMap<>();
        int i = 0;
        int j = 0;
        try {
            // InputStream in = resource.getInputStream();
            InputStream in = new FileInputStream(basePath + File.separator
                    + templatePath + File.separator + templateImport + File.separator + tmplName);
            XLSReader mainReader = ReaderBuilder.buildFromXML(in);

            List<GoodsCustomer> list = new ArrayList<>();
            List<GoodsCustomer> list1 = new ArrayList<>();


            Map beans = new HashMap();
            beans.put("list", list);
            XLSReadStatus readStatus = mainReader.read(file.getInputStream(), beans);
            if (readStatus.isStatusOK()) {
                for (GoodsCustomer info : list) {
                    GoodsCustomer entity = new GoodsCustomer();
                    entity.setId(IdUtils.fastSimpleUUID());
                    BeanUtils.copyProperties(info, entity, "id");
                    if(StringUtils.isNotBlank(info.getIdx())){
                        if (StringUtils.isNotBlank(info.getName())) {
                            if (StringUtils.isNotBlank(errortext)) {
                                map.put("errorText", errortext);
                                map.put("num", i);
                                return map;
                            } else {
                                list1.add(entity);
                            }
                        }
                    } else {
                        errortext += "序号为" + info.getIdx() + "行数据，客户名称不能为空，请填写后导入！";
                    }
                }
            }
            if (StringUtils.isBlank(errortext)) {
                for (GoodsCustomer info : list1) {
                    GoodsCustomer contact1=new GoodsCustomer();
                    contact1.setName(info.getName());
                    List<GoodsCustomer> contactList=goodsCustomerMapper.selectList(contact1);
                    if(contactList.size()>0){
                        //info=contactList.get(0);
                        info.setId(contactList.get(0).getId());
                        j+= this.update(info);
                    }else{
                        i += this.insert(info);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("errorText", errortext);
        map.put("num", i);
        map.put("numupdate", j);
        return map;
    }




}
